//定制请求的实例
//导入axios 需要下载对应的包  npm install axios
import { userTokenStore } from '@/store/token';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router/index';
//定义一个变量,记录公共的前缀
const baseURL = '/api';
const instance = axios.create({baseURL})

//添加请求拦截器
instance.interceptors.request.use(
    config=>{
        const tokenStore = userTokenStore();
        if(tokenStore.token){
            config.headers.Authorization = tokenStore.token;
        }
        return config;        
    },
    err=>{
        ElMessage('请求拦截器发生错误');
        return Promise.reject(err);
    }
)
//添加响应拦截器
instance.interceptors.response.use(
    res=>{
        if(res.data.code != 0){
            console.log(res);
            return res.data;
        }
        ElMessage(res.data.message?res.data.message:'操作失败');
        return Promise.reject(res.data);
    },
    err=>{
        //如果响应状态码为401
        if(err.response.status === 401){
            ElMessage('请先登录');
            router.push('/login');
        }else{
            ElMessage('服务异常');
            return Promise.reject(err);
        }
    }
)

export default instance;